﻿namespace LS.Nc6.Web.Entry.Areas.Systems.Controllers
{
    [Route("[area]/[controller]/[action]")]
    [Area("Systems")]
    [ApiDescriptionSettings("Default")]
    public class RoleController : BaseAdminController
    {

        #region MenuController
        private readonly ISysRoleService _roleService;
        private readonly ISysMenuService _menuService;
        private readonly ISysFunctionService _functionService;
        private readonly ICache _cache;
        public RoleController(ISysMenuService menuService, ISysRoleService roleService, ISysFunctionService functionService, IOptions<CacheOptions> cacheOptions, Func<string, ISingleton, object> resolveNamed)
            : base(cacheOptions, resolveNamed)
        {
            _roleService = roleService;
            _menuService = menuService;
            _functionService = functionService;
            _cache = resolveNamed(cacheOptions.Value.CacheType.ToString(), default) as ICache;
        }

        #endregion

        #region 页面
        public ActionResult Index()
        {
            SysPower(SysMenuConstant.MENU_ROLE_MANAGE, SysMenuConstant.FUN_SELECT, UserInfo.ID.ToString());
            return View();
        }

        public async Task<ActionResult> CreateRole()
        {
            SysPower(SysMenuConstant.MENU_ROLE_MANAGE, SysMenuConstant.FUN_ADD, UserInfo.ID.ToString());
            var model = new SysRoleEntity();
            ViewBag.MenuFunList =JsonSerializer.Serialize(await _functionService.List(a=>true, (a) => new { a.Id }), CommonMethodHelper.MyJsonOptions);
            model.Isenable = true;
            return View("EditRole", model);
        }

        public async  Task<ActionResult> EditRole(long id)
        {
            SysPower(SysMenuConstant.MENU_ROLE_MANAGE, SysMenuConstant.FUN_UPDATE, UserInfo.ID.ToString());
            var model = await _roleService.GetByIdAsync(id);
            if (model == null)
            {
                return ErrorCustomMsg(ResponseHelper.NONEXISTENT);
            }
            ViewBag.MenuFunList = JsonSerializer.Serialize(await _functionService.List(a=>true, (a) => new { a.Id }), CommonMethodHelper.MyJsonOptions);
            return View(model);
        }
        #endregion



        #region 公共方法
        /// <summary>
        /// 获取角色list
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<ResponseResultDataList> GetList()
        {
            string rolename = RequestHelper.FilterParam(Request.Query["rolename"]);

            var page = Request.Query["page"].ToString().GetQueryValueOrNull<int>(1);
            var limit = Request.Query["limit"].ToString().GetQueryValueOrNull<int>(20);
            string field = Request.Query["field"];
            string order = Request.Query["order"];

            var expable = Expressionable.Create<SysRoleEntity>();
            expable.AndIF(!string.IsNullOrEmpty(rolename), a => a.RoleName.Contains(rolename));
            var exp = expable.ToExpression();

            var strField = RequestHelper.FilterParam(field);
            var strOrder = RequestHelper.FilterParam(order);

            Expression<Func<SysRoleEntity, object>> expressionOrder;
            if (string.IsNullOrEmpty(strField) || string.IsNullOrEmpty(strOrder))
            {
                expressionOrder = (a) => new { a.Id };
            }
            else
            {
                //实现字段排序
                expressionOrder = (a) => new { a.CreateDate };
            }
            var result = await _roleService.PageList(exp, page, limit, expressionOrder);

            return new ResponseResultDataList { code = ResponseHelper.SEUCCESSCODE, message = "请求成功", data = result.Items, count = result.TotalCount };

        }

        /// <summary>
        /// 获取所有菜单
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<ResponseResultDataList> GetRoleAllMenu()
        {
            string rolecode = RequestHelper.FilterParam(Request.Query["roleCode"]);
            return new ResponseResultDataList { code = ResponseHelper.SEUCCESSCODE, message = "请求成功", data =await GetMenuListAllData(rolecode), count = 100 };
        }

        [HttpGet]
        public async Task<ResponseResultDataList> GetTreeAllRole()
        {
            string rolecode = RequestHelper.FilterParam(Request.Query["rolecode"]);
            return new ResponseResultDataList { code = ResponseHelper.SEUCCESSCODE, message = "请求成功", data =await GetRoleListAllTreeData(rolecode), count = 100 };
        }
        [HttpGet]
        public async Task<ResponseResultDataList> GetAllRoleCondition()
        {
            string rolename = RequestHelper.FilterParam(Request.Query["keyword"]);
            return new ResponseResultDataList { code = ResponseHelper.SEUCCESSCODE, message = "请求成功", data = await GetRoleCondition(rolename), count = 100 };
        }
        /// <summary>
        /// 保存角色
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<ResponseResult> SaveRoleMenu([FromBody]SysRoleEntity model)
        {
            bool power = true;
          
            if (string.IsNullOrWhiteSpace(model.RoleCode))
            {
                return ResponseHelper.MessageResult(ResponseHelper.PARAMETER_BMBNWK);
            }

            List<SysRoleMenuEntity> list = new List<SysRoleMenuEntity>();
            //处理菜单 功能
            var listfuncode = CommonUtil.GetStringListNoNull(model.FunCode);
            if (model.MenuCode != null)
            {
                var menucode = model.MenuCode.GetStringArrayNoNull();
                foreach (var item in menucode)
                {
                    list.Add(new SysRoleMenuEntity
                    {
                        MenuCode = item,
                        RoleCode = model.RoleCode,
                        FunCode = GetRoleMenuFun(listfuncode, item)
                    }) ;
                }
            }
            int result = 0;
            if ( await _roleService.ExistsRoleCode(model.Id.ToString(), model.RoleCode)){
                return ResponseHelper.MessageResult(ResponseHelper.PARAMETER_BMYCZ);
            }
            if (model.Id > 0)
            {
                power = SysPower(SysMenuConstant.MENU_ROLE_MANAGE, SysMenuConstant.FUN_UPDATE, UserInfo.ID.ToString(), false);
                if (!power)
                {
                    return ResponseHelper.MessageResult(ResponseHelper.PERMISSION_QXZU);
                }
                var editmodel =await _roleService.GetByIdAsync(model.Id);
                if (editmodel == null || editmodel.IsDeleted==1)
                {
                    return ResponseHelper.MessageResult(ResponseHelper.OPERATE_SJYSC);
                }
                CommonMethodHelper.MapperToModel(editmodel, model, null);
              
                result =await _roleService.UpdateRoleMenu(editmodel, list);
            }
            else
            {
                power = SysPower(SysMenuConstant.MENU_ROLE_MANAGE, SysMenuConstant.FUN_ADD, UserInfo.ID.ToString(), false);
                if (!power)
                {
                    return ResponseHelper.MessageResult(ResponseHelper.PERMISSION_QXZU);
                }
                
                result = await _roleService.InsertRoleMenu(model, list);
            }
            if (result > 0)
            {
                await _cache.DelByPatternAsync("CurentMenu_" + UserInfo.ID.ToString());
                await _cache.DelByPatternAsync("CurentPower_" + UserInfo.ID.ToString());
                
            }
            return ResponseHelper.SaveResult(result);

        }

        
        
        /// <summary>
        /// 删除菜单
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<ResponseResult> DelRole([FromBody] DeletDataInput input)
        {
            var r = SysPower(SysMenuConstant.MENU_ROLE_MANAGE, SysMenuConstant.FUN_DELETE, UserInfo.ID.ToString(), false);
            if (!r)
            {
                return ResponseHelper.MessageResult(ResponseHelper.PERMISSION_WSCQX);
            }
            if (string.IsNullOrEmpty(input.Ids))
            {
                return ResponseHelper.MessageResult(ResponseHelper.PARAMETER_CSCW);
            }
            int result = await _roleService.DeleteAsync(input.Ids);
            return ResponseHelper.DeleteResult(result);
           
        }
        #endregion

        #region 私有方法
        private async Task< List<Hashtable>> GetMenuListAllData(string roleCode)
        {
            List<Hashtable> lsetm = new List<Hashtable>();
          
            var  menulist = await _menuService.MenuList(a => a.Isenable==true);
            List<SysRoleMenuEntity> rolemenu = null;
            if (!string.IsNullOrEmpty(roleCode))
            {
                rolemenu = await _roleService.RoleMenuList(roleCode);
            }

            foreach (var item in menulist)
            {
                Hashtable etm = new Hashtable();
                etm.Add("id", item.Id);
                etm.Add("name", item.MenuName);
                etm.Add("menuCode", item.MenuCode);
                etm.Add("pId", item.ParentId);
                etm.Add("funcode", item.Funcode);
                etm.Add("open", true);
                if (rolemenu!=null && rolemenu.Where(w=>w.MenuCode== item.MenuCode).Count()>0)
                {
                    etm.Add("LAY_CHECKED", true);
                    var children = rolemenu.Where(w => w.MenuCode == item.MenuCode);
                    StringBuilder sbch = new StringBuilder();
                    foreach (var chd in children)
                    {
                        sbch.Append(chd.FunCode + ",");
                    }
                    etm.Add("rolefuncode", sbch.ToString());
                }
                lsetm.Add(etm);
            }
            return lsetm;
        }

   

        private async Task<List<Hashtable>> GetRoleListAllTreeData(string roleCode)
        {
            List<Hashtable> lsetm = new List<Hashtable>();
            string[] rolearry = CommonUtil.GetStringArrayNoNull(roleCode);
            var rolelist = await _roleService.List(a=>true,a=>a.RoleSeq);

            foreach (var item in rolelist)
            {
                Hashtable etm = new Hashtable();
                etm.Add("id", item.RoleCode);
                etm.Add("name", item.RoleName);
                if (rolearry.Contains(item.RoleCode))
                {
                    etm.Add("checked", true);
                }
                lsetm.Add(etm);
            }
            return lsetm;
        }
        /// <summary>
        /// 获取菜单功能关联
        /// </summary>
        /// <param name="menufun"></param>
        /// <returns></returns>
        private string GetRoleMenuFun(List<string> listfuncode,string menucode)
        {
            List<string> ls = new List<string>();
            foreach (var item in listfuncode)
            {
                var mf = item.Split('-');
                if (mf[0]== menucode)
                {
                    ls.Add(mf[1]);
                }
            }
            return string.Join(",", ls);
;
        }

        private async Task<List<Hashtable>> GetRoleCondition(string rolename)
        {
            List<Hashtable> lsetm = new List<Hashtable>();
            var expable = Expressionable.Create<SysRoleEntity>();
            expable.AndIF(!string.IsNullOrEmpty(rolename),a=>a.RoleName.Contains(rolename));
            var exp = expable.ToExpression();
            var rolelist = await _roleService.List(exp,null);

            foreach (var item in rolelist)
            {
                Hashtable etm = new Hashtable();
                etm.Add("value", item.RoleCode);
                etm.Add("name", item.RoleName);
                etm.Add("selected", "");
                etm.Add("disabled", "");
                lsetm.Add(etm);
            }
            return lsetm;
        }
        #endregion

    }
}